package main

import (
	"fmt"
	"net/http"
	"runtime"
	"syscall"
)

/*
https://tip.golang.org/pkg/runtime/#LockOSThread

LockOSThread wires the calling goroutine to its current operating system thread.
The calling goroutine will always execute in that thread, and no other goroutine will execute in it,
until the calling goroutine has made as many calls to UnlockOSThread as to LockOSThread.
If the calling goroutine exits without unlocking the thread, the thread will be terminated.
A goroutine should call LockOSThread before calling OS services or non-Go library functions that depend on per-thread state.
*/

/*
如果想要使用 runtime.LockOSThread 实现优先级效果, 不能使用 select, time.sleep 之类的调用.
这些调用会依赖于 go 本身的 heap 定时器, 需要使用 syscall 来实现, 例如使用 epoll 配合 SYS_TIMER_SETTIME
*/

func main() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	fmt.Println("main thread:", syscall.Gettid())

	http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("working thread:", syscall.Gettid())
	})

	http.ListenAndServe(":11990", nil)
}
